package com.morningstar.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.morningstar.common.dao.entity.CommonQuery;
import com.morningstar.common.result.Result;
import com.morningstar.system.controller.result.ArcoDesignFile;
import com.morningstar.system.controller.result.FileUploadResult;
import com.morningstar.system.dao.entity.SysFile;
import com.morningstar.system.service.SysFileBizService;
import com.morningstar.system.service.SysFileService;
import com.morningstar.system.service.SysUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

import static com.morningstar.common.constants.permission.PermissionConstants.*;

/**
 * 文件管理接口
 */
@Slf4j
@RestController
@RequestMapping(value = "/system/file")
public class SysFileController {

    private static final String PERMISSION = "system.file";
    private static final String PERMISSION_LIST = PERMISSION + LIST;
    private static final String PERMISSION_DETAIL = PERMISSION + DETAIL;
    private static final String PERMISSION_DELETE = PERMISSION + DELETE;

    @Resource
    private SysFileService fileService;

    @Resource
    private SysFileBizService fileBizService;

    @Resource
    private SysUserService userService;

    /**
     * 文件列表
     *
     * @param commonQuery 查询条件实体
     * @return 分页
     */
    @PostMapping("/list")
    @SaCheckPermission(PERMISSION_LIST)
    public Result<IPage<SysFile>> list(@RequestBody CommonQuery<SysFile, SysFile> commonQuery) {
        SysFile query = commonQuery.getQuery();
        LambdaQueryWrapper<SysFile> queryWrapper = new LambdaQueryWrapper<>();
        if (query != null) {
            queryWrapper.like(StringUtils.isNotBlank(query.getFileName()), SysFile::getFileName, query.getFileName());
            queryWrapper.like(StringUtils.isNotBlank(query.getFileType()), SysFile::getFileType, query.getFileType());
        }
        queryWrapper.orderByDesc(SysFile::getCreateTime);
        IPage<SysFile> page = fileService.page(commonQuery.getPage(), queryWrapper);
        List<Long> fileIds = page.getRecords().stream().map(SysFile::getFileId).toList();
        Map<Long, List<String>> fileBizMap = fileBizService.selectFileBizMap(fileIds);
        Map<Long, String> userIdAndName = userService.selectUserIdAndName();
        page.getRecords().forEach(sysFile -> {
            sysFile.setFileSizeShow(getFileSize(sysFile.getFileSize()));
            sysFile.setCreateByName(userIdAndName.get(sysFile.getCreateBy()));
            sysFile.setFileBizNames(fileBizMap.get(sysFile.getFileId()));
        });
        return Result.successData(page);
    }

    /**
     * 文件详情
     *
     * @param fileId 文件信息
     * @return 文件详情
     */
    @GetMapping("/detail")
    @SaCheckPermission(PERMISSION_DETAIL)
    public Result<SysFile> detail(@RequestParam("fileId") Long fileId) {
        SysFile sysFile = fileService.getById(fileId);
        if (sysFile != null) {
            Map<Long, String> userIdAndName = userService.selectUserIdAndName();
            sysFile.setFileSizeShow(getFileSize(sysFile.getFileSize()));
            sysFile.setCreateByName(userIdAndName.get(sysFile.getCreateBy()));
            sysFile.setFileBizNames(fileBizService.selectBizNameList(fileId));
            sysFile.setPreviewUrl(fileService.getUrlPrefix() + sysFile.getFilePath());
        }
        return Result.successData(sysFile);
    }

    /**
     * 删除文件
     *
     * @param fileId 文件Id
     * @return 删除结果
     */
    @GetMapping("/delete")
    @SaCheckPermission(PERMISSION_DELETE)
    public Result<Object> delete(@RequestParam("fileId") Long fileId) throws Exception {
        fileService.removeFile(fileId);
        return Result.successNoData();
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 文件上传结果
     * @throws Exception 异常信息
     */
    @PostMapping("/upload")
    @SaCheckLogin
    public Result<FileUploadResult> upload(@RequestParam("file") MultipartFile file) throws Exception {
        return Result.successData(fileService.uploadFile(file));
    }

    @GetMapping("/download")
    public void download(@RequestParam("fileId") Long fileId, HttpServletResponse res) {
        fileService.downloadFile(fileId, res);
    }
    /**
     * 根据文件Id获取文件信息  arco design 文件列表
     *
     * @param fileIds 文件Id
     * @return 文件信息
     */
    @PostMapping("/list/arco")
    @SaCheckLogin
    public Result<List<ArcoDesignFile>> listArco(@RequestBody List<Long> fileIds) {
        if (CollUtil.isEmpty(fileIds)) {
            return Result.successData(CollUtil.newArrayList());
        }
        String urlPrefix = fileService.getUrlPrefix();
        List<SysFile> sysFiles = fileService.listFile(fileIds);
        List<ArcoDesignFile> result = sysFiles.stream().map(sysFile -> ArcoDesignFile.success(sysFile, urlPrefix)).toList();
        return Result.successData(result);
    }

    private String getFileSize(Long size) {
        if (size < 1024) {
            return size + "B";
        }
        long kb = size / 1024;
        if (kb < 1024) {
            return kb + "kB";
        }
        long mb = kb / 1024;
        if (mb < 1024) {
            return mb + "MB";
        }
        return mb / 1024 + "GB";
    }
}
